$(function () {

    var dg1 = htmlParam.debug1;
    var pidSetting = '', uiFrame = '';
    uiFrame += '<div data-role="page" id="pageone">';

    pidSetting += '<div data-role="panel" id="settings"><h2>设置参数</h2>';
    pidSetting += '<form action="/api/remote/" target="_self" novalidate="true">';
    pidSetting += '<div class="ui-field-contain">';
    pidSetting += '<label for="maxt">加热到最高温度:</label><input name="maxt"  type="number">';
    pidSetting += '<label for="tem3">停止后降至几度开炉:</label><input name="tem3"  type="number">';
    pidSetting += '<label for="optime1">设置开炉秒数:</label><input name="optime1"  type="number">';
    pidSetting += '<label for="Z2">前200度每30秒升几度:</label><input name="Z2"  type="number">';
    pidSetting += '<label for="Z4">前200-400度每30秒升几度:</label><input name="Z4"  type="number">';
    pidSetting += '<label for="Z6">前400-600度每30秒升几度:</label><input name="Z6"  type="number">';
    pidSetting += '<label for="Z8">前600-800度每30秒升几度:</label><input name="Z8"  type="number">';
    pidSetting += '<label for="P">pid比例参数:</label><input name="P" type="number">';
    pidSetting += '<label for="D">pid微分参数:</label><input name="D" type="number">';
    pidSetting += '</div>';
    pidSetting += '<input id="reset" type="button" value="重置">';
    pidSetting += '<input id="submitData" type="submit" value="提交">';
    pidSetting += '</form>';
    pidSetting += '</div>';

    uiFrame += pidSetting;
    uiFrame += '<div class="ui-panel-wrapper"><div id="mainHead" data-role="header"><a href="#settings" class="ui-btn ui-corner-all ui-shadow ui-icon-gear ui-btn-icon-left">设置</a><h1>温控首页</h1>'
    uiFrame += '<a id="chartBtn" class="ui-btn ui-icon-grid ui-corner-all ui-shadow ui-btn-icon-left">曲线</a></div>'
    uiFrame += '<div data-role="main">'
    uiFrame += '<h1 id="temp">温度:<span style="color:red">' + (htmlParam.tem1).toFixed(2) + '</span>度</h1>'
    uiFrame += '温度控制：<button data-inline="true" id="control">' + htmlParam.button + '</button>'

    uiFrame += '<button data-inline="true" onclick="window.location=\'/api/remote/\'">刷新</button>'
    uiFrame += '<button id="warn" data-inline="true">{[0]}</button>'.format(htmlParam.isWarn ? '已预警' : '未预警')
    uiFrame += '<br>打开炉盖：<button data-inline="true" onclick="window.location=\'/api/remote/open60\'">全开</button>'
    uiFrame += '<button data-inline="true" onclick="window.location=\'/api/remote/open1\'">开1秒</button>'
    uiFrame += '<button data-inline="true" onclick="window.location=\'/api/remote/open2\'">开2秒</button>'
    uiFrame += '<button data-inline="true" onclick="window.location=\'/api/remote/open23\'">开23秒</button>'
    uiFrame += '<br>关闭炉盖：<button data-inline="true" onclick="window.location=\'/api/remote/close60\'">全关</button>'
    uiFrame += '<button data-inline="true" onclick="window.location=\'/api/remote/close1\'">关1秒</button>'
    uiFrame += '<button data-inline="true" onclick="window.location=\'/api/remote/close2\'">关2秒</button>'
    uiFrame += '<button id="stop">停止</button>';

    uiFrame += '加热时间<h2>' + parseInt(htmlParam.m / 3600) + ':' + parseInt(htmlParam.m % 3600 / 60) + ':' + parseInt(htmlParam.m % 60) + '</h2>'
    uiFrame += '停止时间<h2>' + parseInt(htmlParam.stopT / 3600) + ':' + parseInt(htmlParam.stopT % 3600 / 60) + ':' + parseInt(htmlParam.stopT % 60) + '</h2>'
    uiFrame += '运行时间<h2>' + parseInt(htmlParam.t1 / 3600) + ':' + parseInt(htmlParam.t1 % 3600 / 60) + ':<b>' + parseInt(htmlParam.t1 % 60) + '</b></h2><h3>设定温度：' + htmlParam.maxt + '度</h3><h4>ct=' + htmlParam.ct + '</h4>'
    uiFrame += '<button class="ui-btn ui-icon-lock ui-btn-icon-left"onclick="window.location=\'/api/remote/start\'">解锁</button>'
    uiFrame += '<p style="color:cyan">' + htmlParam.debug1 + '</p>'
    uiFrame += '</div><div data-role="footer"><h1>好好学习，天天向上！</h1></div></div></div>'

    uiFrame += '<div data-role="page" id="pagetwo">'
    uiFrame += '<div data-role="header"><a href="#pageone" class="ui-btn ui-corner-all ui-shadow ui-icon-back ui-btn-icon-left">返回</a><h1>升温曲线图</h1>'
    uiFrame += '<a href="#myPopup" data-position-to="window" data-transition="fade" data-rel="popup" class="ui-btn ui-icon-search ui-btn-icon-left">日期</a></div>'
    uiFrame += '<div data-role="main" class="ui-content">'
    uiFrame += '<div id="myCharts"></div>'
    uiFrame += '<div id="myTable" style="overflow: scroll"></div>'
    uiFrame += '</div>'

    uiFrame += '<div data-role="popup" id="myPopup" class="ui-content">'
    uiFrame += '<a href="#" id="queryBack" data-rel="back" class="ui-btn ui-corner-all ui-shadow ui-btn ui-icon-delete ui-btn-icon-notext ui-btn-right">关闭</a>'
    uiFrame += '<label for="createTime_start">查询起始:</label><input name="createTime_start" id="createTime_start">'
    uiFrame += '<label for="createTime_end">查询结束:</label><input name="createTime_end" id="createTime_end">'
    uiFrame += '<button id="queryChart">确定</button>';
    uiFrame += '</div>'

    uiFrame += '</div>'
    $('body').html(uiFrame);
    if (!/开炉/.test(dg1)) {
        if ($('#control').text() == "已打开") dg1 = "在升温";
        else dg1 = "暂停加热";
    } else if(htmlParam.isWarn)
        $.get('/cgi-bin/warn.py', function (data) {
            alert(data.result)
        });

    $('#temp').html(function (i, origin) {
        return origin + '(<i>' + dg1 + '</i>)'
    });
    $('#queryChart').click(function (e) {
        let queryParam = {}, start = $('#createTime_start').val(), end = $('#createTime_end').val()
        if (start) queryParam.createTime_start = start;
        if (end) queryParam.createTime_end = end;
        if (!$.isEmptyObject(queryParam)) {
            $('#queryBack').click()
            console.log(queryParam)
            initMyChart(queryParam)
        } else alert('至少输入起始日期！')
    })
    $('#chartBtn').click(function (e) {
        initMyChart({createTime_start: dateFtt('yyyy-MM-dd hh:mm:ss', new Date(new Date().getTime() - 1000 * 3600 * 10))})
        location = "#pagetwo"
    })
    $('#warn').click(function (e) {
        if (window.confirm("你确认要开/关预警？"))
            $.get('/cgi-bin/warn.py?sw=' + !htmlParam.isWarn * 2, data => {
                htmlParam.isWarn = Boolean(data.result.match(/启动/));
                $(this).text(htmlParam.isWarn ? '已预警' : '未预警')
                alert(data.result)
            });
    });
    $('#control').css('text-shadow', '0px 0px 5px #f00').click(function () {
        if (window.confirm("你确认要操作？")) {
            window.location = "/api/remote/sw";
            if ($('#control').text() == "已关闭")
                $.get('/cgi-bin/warn.py?sw=2', function (data) {
                    alert(data.result)
                });
            // 清表
            // $.get('/api/clear_table', function (data) {
            //     console.log(data)
            // })
        }
    });


    function tmr() {
        $("i").toggleClass("neon5");
        $("h2:last").html(function (i, orig) {
            var time = $(this).text().match(/(\d+):(\d+):(\d+)/);
            time[3] = time[3] * 1 + 1;
            if (time[3] * 1 == 60) {
                time[2] = time[2] * 1 + 1;
                time[3] = 0;
            }
            if (time[2] * 1 == 60) {
                time[1] = time[1] * 1 + 1;
                time[2] = 0;
            }
            return time[1] + ":" + time[2] + ":" + time[3];
        })
    }

    setInterval(tmr, 1000);
    $('#stop').click(function () {
        if (dg1 != "已开炉") window.location = "/api/remote/stop";
        else window.location = "/api/remote/";
    });
    $('#submitData').click(function () {
        if (!confirm('确定保存？')) return false;
    });

    $('#reset').click(function () {
        $('.ui-field-contain input').off('change').on('change', function (e) {
            this.value = (this.value * 1).toFixed(2)
        }).each(function (i, v) {
            v.value = (sysParam[v.name] || 0).toFixed(2);
        });
    }).click();

});

String.prototype.format = function (args) {
    if (arguments.length > 0) {
        var result = this;
        if (arguments.length == 1 && typeof (args) == "object") {
            if ($.isArray(args) == false) {
                result = result.replace(/\{\[(\w+)\]\}/g, function () {
                    return args[arguments[1]] || '';
                });

            } else if ($.isArray(args) == true) {
                for (var i = 0; i < args.length; i++) {
                    if (args[i] == undefined) {
                        return "";
                    } else {
                        var reg = new RegExp("\\{\\[" + i + "\\]\\}", "g");
                        result = result.replace(reg, args[i]);
                    }
                }
            }

        } else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] == undefined) {
                    return "";
                } else {
                    var reg = new RegExp("\\{\\[" + i + "\\]\\}", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
        return result;
    } else {
        return this;
    }
};

function dateFtt(fmt, date) { //author: meizz
    var o = {
        "M+": date.getMonth() + 1,                 //月份
        "d+": date.getDate(),                    //日
        "h+": date.getHours(),                   //小时
        "m+": date.getMinutes(),                 //分
        "s+": date.getSeconds(),                 //秒
        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
        "S": date.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
